<?php
/**
 * MEDIA
 */
class Media
{
	public static function upload ($image_config = NULL)
	{
		$keys = array_keys($_FILES);
		if (empty($keys))
            return array('', '');
			//throw new Exception_Warn('没有上传媒体文件');

		return Media::save_upload_file($keys[0], $image_config);
	}

	public static function save_image_from_file ($imageFilePath, $image_config = NULL)
    {
        if (! file_exists($imageFilePath))
        {
            Kohana::$log->add(Log::ERROR, "FILE NOT FOUND: $imageFilePath");
            return array('', '');
        }

        $image_info     = getimagesize($imageFilePath);
        $upfile['type'] = $image_info['mime'];
        Kohana::$log->add(Log::ERROR, "IMAGE INFO: ". print_r($image_info, TRUE));
        $suffix         = ltrim(image_type_to_extension($image_info['2']), '.');
        Kohana::$log->add(Log::ERROR, "IMAGE SUFFIX: $suffix ");


		$webdir     = Kohana::config('env.upload.mediaurl');
		$updirMain  = Kohana::config('env.upload.mediadir');
		list($updirSub, $md5name) = self::build_sub_dirname($imageFilePath, $updirMain, TRUE);
        $newname    = $md5name.'.'.$suffix;
		$webdir     = trim($webdir, '/');
		$updirMain  = trim($updirMain, '/');
		$updirAbs   = DOCROOT."/$updirMain/$updirSub";

        @rename ($imageFilePath, "$updirAbs/$newname");
        if (file_exists("$updirAbs/$newname"))
            @chmod ("$updirAbs/$newname", 0644);

		$file_url = "/$webdir/$updirSub/$newname";
		$file_pos = "/$updirMain/$updirSub/$newname";
		$location = DOCROOT.$file_pos;

		if (file_exists($location))
        {
            if ($image_config)
                self::resize_image($location, $image_config, $suffix);
			return array($file_url, $file_pos);
        }
		else
            return array('', '');
    }


	public static function save_upload_file ($input_key_name, $image_config = NULL)
    {
        $upfile = Arr::get($_FILES, $input_key_name);
        if (empty($upfile) || empty($upfile['name']) || $upfile['error'] != 0)
            return array('', '');
            //throw new Exception_Warn("无效的媒体文件");


        $upload_is_image = TRUE;

        if (strpos($upfile['type'], 'application/') === 0)
        {
            $upload_is_image = FALSE;
		    $items   = explode('.', $upfile['name']);
            $suffix  = $items[count($items) - 1];
            $suffix  = strtolower($suffix);
        }
        //android上传的$_FILES里的mime错误或是上传的图片没有后缀名
        else if (strpos($upfile['type'], 'image/') === false || strpos($upfile['name'], '.') === false)
        {
            $image_info     = getimagesize($upfile['tmp_name']);
            $upfile['type'] = $image_info['mime'];
            $suffix         = ltrim(image_type_to_extension($image_info['2']), '.');
        }
        else
        {
		    $items   = explode('.', $upfile['name']);
            $suffix  = $items[count($items) - 1];
            $suffix  = strtolower($suffix);
        }
        /*
		if (! in_array($suffix, Kohana::config('env.upload.mediatypes')))
        {
            return array('', '');
			//throw new Exception_Warn("无效的媒体格式");
        }
        */

        //$newname = md5(user::current_user_id().$upfile['name'].time()).'.'.$suffix;
		$webdir     = Kohana::config('env.upload.mediaurl');
		$updirMain  = Kohana::config('env.upload.mediadir');
		list($updirSub, $md5name) = self::build_sub_dirname($upfile['name'], $updirMain, TRUE);
        $newname    = $md5name.'.'.$suffix;
		$webdir     = trim($webdir, '/');
		$updirMain  = trim($updirMain, '/');
		$updirAbs   = DOCROOT."/$updirMain/$updirSub";

		Upload::save($upfile, $newname, $updirAbs);

		//$domain   = Kohana::config('domain.img');
		//$file_url = "http://$domain/$webdir/$updirSub/$newname";
		$file_url = "/$webdir/$updirSub/$newname";
		$file_pos = "/$updirMain/$updirSub/$newname";
		$location = DOCROOT.$file_pos;

		if (file_exists($location))
        {
            if ($image_config && $upload_is_image)
                self::resize_image($location, $image_config, $suffix);
			return array($file_url, $file_pos);
        }
		else
            return array('', '');
			//throw new Exception_Warn("媒体文件写错误");
    }


	
	public static function build_sub_dirname($filename, $updir, $create_dir = TRUE)
	{
		$key = uniqid().time().$filename;
		$md5 = md5($key);
		$sub1 = substr($md5, 0, 2);
		$sub2 = substr($md5, 2, 1);
		$dir  = "$sub1/$sub2";

		$absdir = DOCROOT."/$updir/$dir";

		if ($create_dir && ! file_exists($absdir))
		{
			mkdir($absdir, 0777, TRUE);
		}

		return array($dir, $md5);
	}


    private static function resize_image ($location, $config, $suffix)
    {
		if (! in_array($suffix, Kohana::config('env.upload.imagetypes')))
            return;

        try {
            $image = Image::factory($location);
            $image->resize($config['width'], $config['height'], $config['master']);
	        $image->save();

        }
        catch (Exception $e)
        {
            return ;
        }
    }
}
